package model

import (
	"common/helper"
	"database/sql"
	"errors"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
	"github.com/valyala/fasthttp"
	"strconv"
	"time"
)

type CustomserServiceItem struct {
	Id                  uint   `json:"id,omitempty" db:"id" cbor:"id"`
	Avatar              string `json:"avatar" db:"avatar" cbor:"avatar"`
	CustomerServiceName string `json:"customer_service_name" db:"customer_service_name" cbor:"customer_service_name"`
	Title               string `json:"title" db:"title" cbor:"title"`
	CustomerServiceType int    `json:"customer_service_type" db:"customer_service_type" cbor:"customer_service_type"`
	OpenMethod          string `json:"open_method" db:"open_method" cbor:"open_method"`
	CustomerServiceLink string `json:"customer_service_link" db:"customer_service_link" cbor:"customer_service_link"`
	State               int    `json:"state" db:"state" cbor:"state"`
}

type CustomserServiceItemAdd struct {
	Avatar              string `json:"avatar" db:"avatar" cbor:"avatar"`
	CustomerServiceName string `json:"customer_service_name" db:"customer_service_name" cbor:"customer_service_name"`
	Title               string `json:"title" db:"title" cbor:"title"`
	CustomerServiceType int    `json:"customer_service_type" db:"customer_service_type" cbor:"customer_service_type"`
	OpenMethod          string `json:"open_method" db:"open_method" cbor:"open_method"`
	CustomerServiceLink string `json:"customer_service_link" db:"customer_service_link" cbor:"customer_service_link"`
	State               int    `json:"state" db:"state" cbor:"state"`
}

type MailItem struct {
	Id         int    `json:"id" db:"id" cbor:"id"`
	Uid        int    `json:"uid" db:"uid" cbor:"uid"`
	Title      string `json:"title" db:"title" cbor:"title"`
	Content    string `json:"content" db:"content" cbor:"content"`
	ReviewId   string `json:"review_id" db:"review_id" cbor:"review_id"`
	CreateAt   int64  `json:"create_at" db:"create_at" cbor:"create_at"`
	ReviewName string `json:"review_name" db:"review_name" cbor:"review_name"`
	State      int    `json:"state" db:"state" cbor:"state"`
	SysMailId  int    `json:"sys_mail_id" db:"sys_mail_id" cbor:"sys_mail_id"`
}

type CustomserServiceData struct {
	D []CustomserServiceItem `json:"d" cbor:"d"`
	T int64                  `json:"total" cbor:"t"`
	S uint                   `json:"s" cbor:"s"`
}

type MailListData struct {
	D []MailItem `json:"d" cbor:"d"`
	T int64      `json:"total" cbor:"t"`
}

type MailListParam struct {
	Title     string `json:"title"`
	StartTime string `json:"start_time"`
	EndTime   string `json:"end_time"`
	Page      int    `json:"page"`
	PageSize  int    `json:"page_size"`
	OrderBy   string `json:"orderby"`
	OrderType string `json:"ordertype"` // 查询开始时间
}

func GetCustomServiceList(page, pagesize uint, ex g.Ex) (CustomserServiceData, error) {
	data := CustomserServiceData{}
	t := dialect.From("tbl_cfg_customer_service")
	if page >= 1 {
		query, _, _ := t.Select(g.COUNT(1)).Where(ex).ToSQL()
		err := meta.MerchantDB.Get(&data.T, query)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}
		if data.T == 0 {
			return data, nil
		}
	}

	data.S = pagesize
	offset := (page - 1) * pagesize
	query, _, _ := t.Select("*").Where(ex).Order(g.C("id").Desc()).Offset(offset).Limit(pagesize).ToSQL()
	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func EditGetCustomService(data CustomserServiceItem) error {
	if data.Id > 0 {
		query, _, _ := dialect.Update("tbl_cfg_customer_service").Set(data).Where(g.Ex{"Id": data.Id}).ToSQL()
		_, err := meta.MerchantDB.Exec(query)
		if err != nil {
			return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}
		return nil
	} else {
		winedit := CustomserServiceItemAdd{
			Avatar:              data.Avatar,
			CustomerServiceName: data.CustomerServiceName,
			Title:               data.Title,
			CustomerServiceType: data.CustomerServiceType,
			CustomerServiceLink: data.CustomerServiceLink,
			OpenMethod:          data.OpenMethod,
			State:               data.State,
		}
		query, _, _ := dialect.Insert("tbl_cfg_customer_service").Rows(winedit).ToSQL()
		_, err := meta.MerchantDB.Exec(query)
		if err != nil {
			return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}
		return nil
	}
}

func DeleteCustomService(id string) error {
	ex := g.Ex{
		"id": id,
	}
	query, _, _ := dialect.Delete("tbl_cfg_customer_service").Where(ex).ToSQL()
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return nil
}

// 滚屏配置参数
type BroadcasConfigParam struct {
	Ctype    int    `db:"type" json:"type"`
	Page     int    `json:"page"`
	PageSize int    `json:"page_size"`
	OderBY   string `json:"order_by"`
	OderType string `json:"order_type"`
}

// 滚屏配置
type BroadcasConfigList struct {
	T int              `cbor:"t" json:"total"`
	D []BroadcasConfig `cbor:"d" json:"d"`
}

// 滚屏配置
type BroadcasConfig struct {
	ID        int    `db:"id" json:"id"`
	Ctype     int    `db:"type" json:"type"`
	Phone     string `db:"phone" json:"phone"`
	Amount    string `db:"amount" json:"amount"`
	Content   string `db:"content" json:"content"`
	ConfirmAt int    `db:"confirm_at" json:"confirm_at"`
}

func GetBroadcastList(param BroadcasConfigParam, ctx *fasthttp.RequestCtx) (BroadcasConfigList, error) {
	data := BroadcasConfigList{}

	where := "1=1"
	oderBy := "confirm_at"
	oderType := "desc"

	if param.Ctype != 0 {
		where += " and type=" + strconv.Itoa(param.Ctype)
	}
	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		return data, nil
	} else if loginUser.Businsess != "" {
		return data, nil
	}

	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}
	order := oderBy + " " + oderType

	table := "tbl_cfg_broadcast_config"
	join := ""

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " " + join + " where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "*"
	query := "select " + field + "  from " + table + " as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, err
	}
	return data, nil
}

func UpdateBroadcastConfig(param BroadcasConfig, isDelete int8) error {
	table := "tbl_cfg_broadcast_config"
	query := ""
	if param.Amount == "" {
		param.Amount = "0"
	}
	record := g.Record{
		"type":    param.Ctype,
		"phone":   param.Phone,
		"amount":  param.Amount,
		"content": param.Content,
	}
	record["confirm_at"] = time.Now().Unix()
	if param.ID > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(record).Where(g.Ex{"id": param.ID}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.ID}).ToSQL()
		}
	} else {
		query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
	}

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func GetMailList(param MailListParam) (MailListData, error) {
	data := MailListData{}
	where := "1=1"
	table := "tbl_member_mail"
	join := ""

	if param.StartTime != "" {
		StartTime, _ := helper.TimeToLocDay(param.StartTime, loc)
		where += " and create_at>='" + strconv.FormatInt(StartTime, 10) + "'"
	}
	if param.EndTime != "" {
		EndTime, _ := helper.TimeToLocDay(param.EndTime, loc)
		where += " and create_at<'" + (strconv.FormatInt(EndTime, 10)) + "'"
	}

	if param.Title != "" {
		where += " and title like '%" + param.Title + "%'"
	}

	oderBy := "id"
	oderType := "desc"
	if param.OrderBy != "" && param.OrderType != "" {
		oderBy = param.OrderBy
		oderType = param.OrderType
	}
	order := oderBy + " " + oderType
	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a where " + where
		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}
		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*"
	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)
	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func MailUpdate(data MailItem, adminid, adminname string) error {
	if data.Id > 0 {
		query, _, _ := dialect.Update("tbl_member_mail").Set(data).Where(g.Ex{"Id": data.Id}).ToSQL()
		_, err := meta.MerchantDB.Exec(query)
		if err != nil {
			return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}
		return nil
	} else {
		dataedit := MailItem{
			Uid:        data.Uid,
			Title:      data.Title,
			Content:    data.Content,
			CreateAt:   time.Now().Unix(),
			ReviewId:   adminid,
			ReviewName: adminname,
			State:      1,
		}
		query, _, _ := dialect.Insert("tbl_member_mail").Rows(dataedit).ToSQL()
		_, err := meta.MerchantDB.Exec(query)
		if err != nil {
			return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}
		return nil
	}
}

func MailDeleteById(id string) error {
	ex := g.Ex{
		"id": id,
	}
	query, _, _ := dialect.Update("tbl_member_mail").Set(g.Record{"state": 3}).Where(ex).ToSQL()
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return nil
}

func GetUnbindControllerList(param CommonParam, ctx *fasthttp.RequestCtx) (UnbindControllerRetData, error) {

	data := UnbindControllerRetData{}
	where := "1=1"
	oderBy := "a.id"
	oderType := "desc"

	if param.Uid != 0 {
		where += " and a.uid=" + strconv.Itoa(param.Uid)
	}
	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}

	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		where += " and b.operator_id=" + loginUser.Operator
	}
	if loginUser.Businsess != "" {
		where += " and b.business_id=" + loginUser.Businsess
	}

	table := "tbl_member_unbind_control_list"

	join := " left join tbl_member_base as b on b.uid=a.uid"          //玩家表
	join += " left join tbl_operator_info as c on c.id=b.operator_id" //渠道表
	join += " left join tbl_business_info as d on d.id=b.business_id" //业务员表

	order := oderBy + " " + oderType

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a " + join + " where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*,ifnull(b.username,'') username,ifnull(b.operator_id,0) operator_id,ifnull(b.business_id,0) business_id,ifnull(c.operator_name,'') operator_name,ifnull(d.account_name,'') as business_name"

	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)
	fmt.Println(query)
	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {

		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func UpdateUnbindController(param UnbindControllerData, isDelete int) error {

	table := "tbl_member_unbind_control_list"
	query := ""
	record := g.Record{
		"uid": param.Uid,
	}
	if isDelete == 0 {
		has := ""
		meta.MerchantDB.Get(&has, fmt.Sprintf("select uid from tbl_member_unbind_control_list where uid='%s'", param.Uid))
		if has != "" {
			return nil
		} else {
			query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
		}
	} else {
		query, _, _ = dialect.Delete(table).Where(g.Ex{"uid": param.Uid}).ToSQL()
	}
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func ExcelOperatorAndBusiness() [][]interface{} {
	exportData := [][]interface{}{}

	//渠道数据
	var operatorList []TblOperatorInfo
	oprList := map[string]string{}
	query := "select * from tbl_operator_info where id<>888888"
	err := meta.MerchantDB.Select(&operatorList, query)
	if err != nil && err != sql.ErrNoRows {
		return exportData
	}
	if len(operatorList) > 0 {

		for _, value := range operatorList {

			oprList[value.Id] = value.OperatorName

			single := []interface{}{
				"渠道",
				value.OperatorName,
				value.OperatorName,
				value.RechargeFee,
				value.WithdrawFee,
				value.ApiFee,
				value.Seamo,
				"",
				"",
				"",
			}
			exportData = append(exportData, single)
		}
	}

	var businessList []TblBusinessInfo
	query = "select * from tbl_business_info where operator_id<>888888"

	err = meta.MerchantDB.Select(&businessList, query)
	if err != nil && err != sql.ErrNoRows {
		return exportData
	}
	if len(businessList) > 0 {
		busList := map[string]string{}
		for _, value := range businessList {
			oprList[value.Id] = value.LoginAccount
		}
		for _, value := range businessList {
			single := []interface{}{
				"业务员",
				value.AccountName,
				value.LoginAccount,
				value.RechargeFee,
				value.WithdrawFee,
				value.ApiFee,
				value.Seamo,
				value.Type,
				oprList[value.OperatorId],
				busList[value.ParentId],
			}
			exportData = append(exportData, single)
		}
	}
	return exportData
}
